<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['jiguandeatil:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:post:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDeleteall"
          v-hasPermi="['jiguandeatil:removeall']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:post:export']"
        >导出</el-button>
      </el-col> -->
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50"></el-table-column>
      <!-- <el-table-column label="机关公务员id" align="center" prop="civil_servants_id" /> -->
      <el-table-column label="部门" align="center" prop="department" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="职务" align="center" prop="position" />
      <el-table-column label="清单类型" align="center" prop="type" />
      <el-table-column label="清单列表" align="center" prop="work_list" />
      <el-table-column align="center" sortable prop="location" label="图片" width="120">
        <template slot-scope="scope">
          <!-- <el-image style="width: 60px; height: 60px" :src="scope.row.location ? scope.row.location : ''">
          </el-image> -->
          <el-popover placement="right" title trigger="hover">
                  <img :src="scope.row.location ? scope.row.location : ''" />
                  <img
                    slot="reference"
                    :src="scope.row.location ? scope.row.location : ''"
                    :alt="scope.row.location"
                    style="max-height: 50px;max-width: 130px"
                  />
                </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['jiguandeatil:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['jiguandeatil:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改正面清单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-steps :active="active" finish-status="success" simple>
        <el-step title="步骤1"></el-step>
        <el-step title="步骤2"></el-step>
      </el-steps>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div style="margin-top: 20px;">
          <div v-show="active == 1">
            <el-form-item label="清单类型" prop="type_id">
              <el-select v-model="form.type_id" placeholder="清单类型" clearable style="width: 100%" @change="nextbtndis">
                <el-option v-for="item in options" :key="item.id" :label="item.type" :value="item.id" />
              </el-select>
            </el-form-item>
          </div>

          <div v-show="active == 2">
            <el-form-item label="清单列表" prop="work_list">
              <el-input v-model="form.work_list" type="textarea" placeholder="请输入清单列表" />
            </el-form-item>

            <el-form-item label="图片" prop="location">
              <div style="display: flex;flex-direction: row;">
                <el-upload ref="upload" action="" :on-exceed="handleExceed" list-type="picture-card"
                  :limit="limitUpload" accept=".jpeg,.icon,.png,.gif,.jpg" :on-preview="handlePreview"
                  :on-remove="handleRemove" :file-list="fileListImg" :on-change="onUploadChangeImg" :auto-upload="false"
                  style="margin-left: 20px;">
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible" append-to-body>
                  <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div v-show="active == 1">
          <el-button style="margin-top: 12px;" @click="next" :disabled="isdisable">下一步</el-button>
        </div>
        <div v-show="active == 2">
          <el-button style="margin-top: 12px;" @click="pre">上一步</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getzhenglist, delUsers, delUser, addUser, updateUser, gettypelist, uploadimg } from "@/api/jiguanorder";

export default {
  name: "Post",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        postCode: undefined,
        postName: undefined,
        status: undefined,
        civilServantsId: '',
        prosCons: '0',
        id: ''
      },
      fileListImg: [],
      limitUpload: 1,
      isdisable: true,
      options: [],
      dialogVisible: false,
      dialogImageUrl: '',
      active: 1,
      pic: '',
      pictureurl: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        type_id: [
          { required: true, message: "清单类型不能为空", trigger: "blur" }
        ],
        work_list: [
          { required: true, message: "清单列表不能为空", trigger: "blur" }
        ],
        // postCode: [
        //   { required: true, message: "岗位编码不能为空", trigger: "blur" }
        // ],
      }
    };
  },
  created() {
    this.getList();
    this.gettypeList();
  },
  methods: {
    /** 查询清单列表 */
    getList() {
      this.loading = true;
      this.queryParams.civilServantsId = this.$route.query.zhengid
      this.queryParams.prosCons = '0'
      getzhenglist(this.queryParams).then(response => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },


    nextbtndis() {
      if (this.form.type_id) {
        this.isdisable = false
      }
      else {
        this.isdisable = true
      }
    },


    //超出最大上传文件数量时的处理方法
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！"
      });
      return;
    },

    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file, fileList) {
      this.form.pic = ''
      this.fileListImg = []
      // console.log(file, fileList);
    },


    //上传图片
    onUploadChangeImg(file) {
      console.log(file, 'file123')
      const _self = this;
      const isZIP = file.raw.type === 'image/jpeg' || file.raw.type === 'image/x-icon' || file.raw.type === 'image/png' || file.raw.type === 'image/gif';
      const isLt1M = file.size / 1024 / 1024 < 20;
      if (!isLt1M) {
        this.$message.error('文件上传大小不能超过20M');
        return;
      }
      if (!isZIP) {
        this.$message.error('文件需求格式错误！');
        return;
      }
      var reader = new FileReader();
      if (isZIP) {
        reader.readAsDataURL(file.raw);
        reader.onload = function (e) {
          _self.pic = e.target.result;
          const formData = new FormData();
          formData.append('file', file.raw);
          // console.log(formData,'formData')
          uploadimg(formData).then(res => {
            _self.form.location = res.url
            // console.log(_self.form.location)
          })
        }
      } else {
        alert('请上传图片格式的文件！');
      }
    },


    //正面清单清单类型下拉列表获取
    gettypeList() {
      // this.queryParams.prosCons = '0'
      gettypelist({ prosCons: '0' }).then(response => {
        this.options = response.data;
      });
    },
    //下一步
    next() {
      if (this.active++ > 2) this.active = 1;
    },
    //上一步
    pre() {
      if (this.active-- < 2) this.active = 1
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        civilServantsId: this.$route.query.zhengid,
        id: undefined,
        // postCode: undefined,
        // postName: undefined,
        del_flag: '0',
        pros_cons: "0",
        type: undefined,
        work_list: undefined,
        location: ''
      };
      this.active = 1
      this.isdisable = true
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加清单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.isdisable=false;
      this.title = "修改清单";
      this.form.work_list = row.work_list
      this.form.id = row.id
      this.form.type_id = row.type
      if (row.location) {
                    this.form.location = row.location
                    this.fileListImg = [{ name: row.location, url: row.location }]
                }
                else {
                    this.fileListImg = []
                }
                this.pictureurl.push(row.location)

      // this.queryParams.civilServantsId = this.$route.query.zhengid
      // this.queryParams.prosCons = '0'
      // getzhenglist(this.queryParams).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改清单";
      // });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.civil_servants_id = this.$route.query.zhengid
            this.form.prosCons = '0'
            this.form.del_flag = '0'
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row.id)
      const postIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除机关公务员编号为"' + postIds + '"的数据项？').then(function () {
        return delUser(postIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },



    /** 批量删除按钮操作 */
    handleDeleteall(row) {
      console.log(row.id)
      const postIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除机关公务员编号为"' + postIds + '"的数据项？').then(function () {
        return delUsers(postIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },




    /** 导出按钮操作 */
    handleExport() {
      this.download('system/post/export', {
        ...this.queryParams
      }, `post_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 105px;
}

.el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
}
</style>